//
//  HOTTolietLIstViewController.m
//  Genpara
//
//  Created by AndyChang.zhang on 14-9-24.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTTolietLIstViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "NSString+extend.h"
#import "HOTToiletViewController.h"

#define kFoursquare_host_url @"https://api.foursquare.com/v2/venues/search"
#define kGoogle_place_url @"https://maps.googleapis.com/maps/api/place/nearbysearch/json"

@interface HOTTolietLIstViewController () <CLLocationManagerDelegate>{
    
    NSMutableArray *_dataList;
    CLLocationManager *clManager;
    CLLocationCoordinate2D userLoc;
    BOOL firstLoaction;
}

@end

@implementation HOTTolietLIstViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNaviTitle:@"便所一覧"];
    
    [self showLoadingWithMessage:MSG_LOADING_LOCATION];
    
    clManager = [[CLLocationManager alloc] init];
    clManager.delegate = self;
    if ([clManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        [clManager requestAlwaysAuthorization];
    }
//    if ([clManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
//        [clManager requestWhenInUseAuthorization];
//    }
    [clManager startUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    if (!firstLoaction && locations.count > 0) {
        
        [self loadingSuccess];
        firstLoaction = YES;
        CLLocation *newLocation = [locations lastObject];
        userLoc = newLocation.coordinate;
        [self requestSearchToiletByLoc:userLoc];
    }
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
//    NSLog(@"%@", error);
    [self loadingSuccess];
    ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE message:MSG_LOAD_LOCATION_FAILED delegate:nil cancelButtonTitle:nil otherButtonTitle:ALERT_BTN_OK];
    
    [popupView showInWindow];
}

#pragma mark - UItableView DataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellId = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    NSDictionary *result = [_dataList objectAtIndex:indexPath.row];
    
    cell.textLabel.text = [[result objectForKey:@"name"] toStr];
    
    cell.detailTextLabel.text = [result objectForKey:@"vicinity"];
    
//    NSDictionary *locationDic = [venue objectForKey:@"location"];
//    
//    cell.detailTextLabel.text = [NSString stringWithFormat:@"【%ldm】%@",
//                                 (long)[[locationDic objectForKey:@"distance"] integerValue],
//                                 [HOTUtils getString:[locationDic objectForKey:@"address"]]];
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataList.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60;
}

#pragma mark - UITableView Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *result = [_dataList objectAtIndex:indexPath.row];
    NSDictionary *geometry = [result objectForKey:@"geometry"];
    HOTToiletViewController *toiletMapVc = [[HOTToiletViewController alloc]
                                            initWithNibName:@"HOTToiletViewController"
                                            bundle:nil
                                            userLoc:userLoc
                                            venue:geometry];
    
    [self.navigationController pushViewController:toiletMapVc animated:YES];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)requestSearchToiletByLoc:(CLLocationCoordinate2D)coor {
    
//    NSString *v = [ZZZUtils formartDate:[NSDate date] withStyle:@"yyyyMMdd"];
//    NSDictionary *param = @{@"radius":@"1500",
//                            @"ll":[NSString stringWithFormat:@"%f,%f",coor.latitude, coor.longitude],
//                            @"query":@"トイレ",
//                            @"limit":@"50",
//                            @"v":v,
//                            @"client_id":kFoursquare_Client_ID,
//                            @"client_secret":kFoursquare_Client_Secret
//                            //,@"intent":@"match"
//                            };
    NSDictionary *param = @{@"language":@"ja",
                            //@"location":[NSString stringWithFormat:@"36.572672,140.643013",coor.latitude, coor.longitude],
                            @"location":[NSString stringWithFormat:@"%f,%f",coor.latitude, coor.longitude],
                            @"keyword":@"トイレ",
                            @"radius":@"50000",
                            @"sensor":@"false",
                            @"key":kGOOGLE_PLACE_API_KEY
                            };
    
    __unsafe_unretained HOTTolietLIstViewController *tempObj = self;
    
    [self showLoadingWithMessage:MSG_SEARCHING];
    [self requestGetWithURL:kGoogle_place_url
                 Parameters:param success:^(NSDictionary * responseObject) {
                     
                     [self loadingSuccess];
                     //解析检索结果
                     [tempObj parseResult:responseObject];
                     
                 } failure:nil];
}

-(void)parseResult:(NSDictionary *)resDic {
    
    NSString *status = [resDic objectForKey:@"status"];
    //NSNumber *kCode = [metaDic objectForKey:@"code"];
    
    if (![status isEqualToString:@"OK"]) {
        
        ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE message:MSG_SEARCH_FAILD delegate:nil cancelButtonTitle:nil otherButtonTitle:ALERT_BTN_OK];
        
        [popupView showInWindow];
        return;
    }
    

        
        NSArray *results = [resDic objectForKey:@"results"];
        
        if (results.count == 0) {
            //没有查询到结果
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE message:MSG_SEARCH_EMPTY delegate:nil cancelButtonTitle:nil otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
            return;
        }
//        _dataList = [NSMutableArray array];
//        for (NSDictionary *venue in venueList) {
//            [_dataList addObject:venue];
//        }
        
//        NSArray *tempList = [results sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//            
//            
//            NSDictionary *locationDic1 = [obj1 objectForKey:@"location"];
//            NSDictionary *locationDic2 = [obj2 objectForKey:@"location"];
//            
//            NSString *dis1 = [locationDic1 objectForKey:@"distance"];
//            NSString *dis2 = [locationDic2 objectForKey:@"distance"];
//            
//            if (dis1 == nil) {
//                
//                return NSOrderedDescending;
//            }
//            if (dis2 == nil) {
//                return NSOrderedDescending;
//            }
//            
//            
//            
//            if ([dis1 integerValue] > [dis2 integerValue]) {
//                
//                return NSOrderedDescending;
//            }
//            
//            if ([dis1 integerValue] < [dis2 integerValue]) {
//                
//                return NSOrderedAscending;
//            }
//            return NSOrderedSame;
//        }];
    
        _dataList = [NSMutableArray arrayWithArray:results];
        
        [_tableView reloadData];
    
    
}

#pragma mark 私有方法

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
